package org.jeecg.modules.yks.config;


import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.jeecg.modules.yks.mqtt.service.MqttReceiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import lombok.extern.slf4j.Slf4j;

/**
 * MQTT接收消息处理
 *
 * @author weir
 *
 *         2019年6月16日 下午2:41:45
 */
@Slf4j
@Configuration
@IntegrationComponentScan
public class MqttConfig {

    private static final String MQTT_RECEIVEDTOPIC = "mqtt_receivedTopic";
    private static final String SP_INBOUND = "_inbound";
    public static final String CHANNEL_NAME_OUT = "mqtt-outbound-channel";
    private static final byte[] WILL_DATA = "offline".getBytes();
    private static final String SPLIT_CHAR = ",";
    private static final String CHANNEL_NAME_IN = "mqtt-inbound-channel";


    private MqttPahoMessageDrivenChannelAdapter adapter;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.pwd}")
    private String password;

    @Value("${mqtt.url}")
    private String hostUrl;

    @Value("${mqtt.client.id}")
    private String clientId;

    @Value("${mqtt.default.topic}")
    private String defaultTopic;

    @Value("${mqtt.will-topic}")
    private String willTopic;

    @Value("${mqtt.completionTimeout}")
    private int completionTimeout;

    @Autowired
    private MqttReceiveService mqttReceiveService;

    /**
     * MQTT连接器选项
     * @return
     */
    @Bean
    public MqttConnectOptions getMqttConnectOptions() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
        mqttConnectOptions.setCleanSession(true);

        //连接用户名
        mqttConnectOptions.setUserName(username);
        //连接用户密码
        mqttConnectOptions.setPassword(password.toCharArray());
        //服务器地址
        if (hostUrl.contains(SPLIT_CHAR)) {
            mqttConnectOptions.setServerURIs(StringUtils.split(hostUrl, SPLIT_CHAR));
        } else {
            mqttConnectOptions.setServerURIs(new String[]{hostUrl});
        }

        // 设置超时时间 单位为秒
        mqttConnectOptions.setConnectionTimeout(10);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线，但这个方法并没有重连的机制
        mqttConnectOptions.setKeepAliveInterval(20);
        // 设置“遗嘱”消息的话题，若客户端与服务器之间的连接意外中断，服务器将发布客户端的“遗嘱”消息。
        mqttConnectOptions.setWill(willTopic, WILL_DATA, 2, false);

        return mqttConnectOptions;
    }

    /**
     * MQTT客户端
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(getMqttConnectOptions());
        return factory;
    }

    /**
     * MQTT消息处理器（生产者）
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(clientId, mqttClientFactory());
        messageHandler.setAsync(true);
        messageHandler.setDefaultTopic(defaultTopic);
        return messageHandler;
    }

    /**
     * MQTT信息通道（生产者）
     * @return
     */
    @Bean
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * 接收通道
     * MQTT信息通道（消费者）
     * @return MessageChannel
     */
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    /**
     * 配置client,监听的topic
     * MQTT消息订阅绑定（消费者）
     * @return MessageProducer
     */
    @Bean
    public MessageProducer inbound() {
        // 可以同时消费（订阅）多个Topic
        adapter = new MqttPahoMessageDrivenChannelAdapter(clientId + SP_INBOUND,
                mqttClientFactory(),
                defaultTopic.contains(SPLIT_CHAR) ? StringUtils.split(defaultTopic, SPLIT_CHAR) : new String[]{defaultTopic});
        adapter.setCompletionTimeout(completionTimeout);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(2);
        // 设置订阅通道
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    /**
     * 通过通道获取数据
     * MQTT消息处理器（消费者）
     * @return MessageHandler
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return new MessageHandler() {
            @Override
            public void handleMessage(final Message<?> message) throws MessagingException {
                final String topic = message.getHeaders().get(MQTT_RECEIVEDTOPIC).toString();
                mqttReceiveService.handlerMqttMessage(topic, message.getPayload().toString());
            }
        };
    }

    /**
     * 动态添加主题
     *
     * @param topicArr 数组
     */
    public void addListenTopic(String[] topicArr) {
        if (topicArr == null || topicArr.length == 0) {
            return;
        }
        if (adapter == null) {
            adapter = new MqttPahoMessageDrivenChannelAdapter(clientId + SP_INBOUND, mqttClientFactory(), "");
        }
        for (String topic : topicArr) {
            try {
                if (!Arrays.asList(adapter.getTopic()).contains(topic)) {
                    adapter.addTopic(topic, 0);
                }
            } catch (Exception e) {
                log.error("MqttConfig---addListenTopic--[]-{}", e);
            }
        }
    }

    /**
     * 动态添加主题
     *
     * @param topic 主题
     */
    public void addListenTopic(String topic) {
        if (StringUtils.isNotBlank(topic)) {
            if (adapter == null) {
                adapter = new MqttPahoMessageDrivenChannelAdapter(clientId + SP_INBOUND, mqttClientFactory(), "");
            }
            try {
                if (!Arrays.asList(adapter.getTopic()).contains(topic)) {
                    adapter.addTopic(topic, 0);
                }
            } catch (Exception e) {
                log.error("MqttConfig---addListenTopic---{}", e);
            }
        }
    }

    /**
     * 删除单个主题
     *
     * @param topic 主题
     */
    public void removeListenTopic(String topic) {
        if (adapter == null) {
            adapter = new MqttPahoMessageDrivenChannelAdapter(clientId + SP_INBOUND, mqttClientFactory(), "");
        }
        try {
            adapter.removeTopic(topic);
        } catch (Exception e) {
            log.error("MqttConfig---removeListenTopic---{}", e);
        }
    }
}
